using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MCromwell.StaffIntranet.Presenters;
using MCromwell.StaffIntranet.DTO;
using System.Collections.Generic;

namespace MCromwell.StaffIntranet.UI
{
    public partial class Edit : Page, IStaffManagementView
    {
        public event EventHandler<StaffManagementInitializeEventArgs> Initialize;
        public event EventHandler<StaffSavedEventArgs> StaffSaved;

        private StaffManagementPresenter presenter;

        protected void Page_Load(object sender, EventArgs e)
        {
            InitializePresenter();
            BindViewEvents();

            if (!IsPostBack)
            {
                AssignPassedStaffIdToViewstate();
                RaiseInitializeEvent();
            }
        }

        private void AssignPassedStaffIdToViewstate()
        {
            int idToPassed = -1;
            string rawId = Request.Params["StaffId"];
            if (!string.IsNullOrEmpty(rawId))
            {
                int.TryParse(rawId, out idToPassed);
            }
            StaffId = idToPassed;
        }

        private int StaffId
        {
            get
            {
                return (int)ViewState["staffid"];
            }
            set
            {
                ViewState["staffid"] = value;
            }
        }

        private void BindViewEvents()
        {
            btnCancel.Click += delegate
            {
                Response.Redirect("~/Search.aspx");
            };

            btnSave.Click += delegate
            {
                RaiseSavedEvent();
            };
        }

        private void RaiseSavedEvent()
        {
            if (StaffSaved != null)
                StaffSaved(this, new StaffSavedEventArgs(RetrieveStaffDetailsFromPage()));
        }

        private StaffDTO RetrieveStaffDetailsFromPage()
        {
            StaffDTO staffDetails = new StaffDTO();

            staffDetails.Id = StaffId;
            staffDetails.FirstName = txtFirstName.Text;
            staffDetails.MiddleName = txtMiddleName.Text;
            staffDetails.LastName = txtLastName.Text;
            staffDetails.EmailAddress = txtEmailAddress.Text;
            staffDetails.TelephoneNumber = txtTelephoneNumber.Text;
            staffDetails.Extension = txtExtension.Text;
            staffDetails.LocationId = int.Parse(ddlLocations.SelectedValue);

            if (chkClearPhoto.Checked)
                staffDetails.Photo.SaveOption = PhotoSaveOption.Clear;
            else
                if (uplImage.HasFile)
                    staffDetails.Photo.Data = uplImage.FileBytes;
                else
                    staffDetails.Photo.SaveOption = PhotoSaveOption.Leave;
                
            return staffDetails;
        }

        private void RaiseInitializeEvent()
        {
            if (Initialize != null)
                Initialize(this, new StaffManagementInitializeEventArgs(StaffId));
        }

        private void InitializePresenter()
        {
            presenter = new StaffManagementPresenter(this);
        }

        public void ShowDetailsOf(StaffDTO staffToManage)
        {
            txtFirstName.Text = staffToManage.FirstName;
            txtMiddleName.Text = staffToManage.MiddleName;
            txtLastName.Text = staffToManage.LastName;
            txtEmailAddress.Text = staffToManage.EmailAddress;
            txtTelephoneNumber.Text = staffToManage.TelephoneNumber;
            txtExtension.Text = staffToManage.Extension;
            ddlLocations.SelectedValue = staffToManage.LocationId.ToString();
            
            imgPhoto.ImageUrl = string.Format("{0}.photo", staffToManage.Id);
            imgPhoto.AlternateText = string.Format("Photo of {0} {1}", staffToManage.FirstName, staffToManage.LastName);
        }

        public void DisplayAvailable(IList<LocationDTO> locations)
        {
            if (!IsPostBack)
            {
                foreach (LocationDTO location in locations)
                {
                    ListItem listItem = new ListItem(location.Value, location.Id.ToString());
                    ddlLocations.Items.Add(listItem);
                }
            }
        }

        public void ResultsOfSave(int staffId, NotificationDTO notification)
        {
            firstnameErrorHighlighter.CheckNotification(notification);
            lastnameErrorHighlighter.CheckNotification(notification);
            emailAddressErrorHighlighter.CheckNotification(notification);
            telephoneNumberErrorHighlighter.CheckNotification(notification);
            extensionErrorHighlighter.CheckNotification(notification);
            loctionErrorHighlighter.CheckNotification(notification);
            errorSummary.DisplaySummaryUsing(notification);

            if (!notification.HasErrors)
            {
                StaffId = staffId;
                RaiseInitializeEvent();
            }
        }
    }
}
